<script setup>
import {
    Edit,
    Delete
} from '@element-plus/icons-vue'
import { ref, computed } from 'vue'
// 导入相关接口
import { getEmployeeList, addEmployeeApi, editEmployeeApi, deleteEmployeeApi } from '@/api/backend/employee.js'
import { ElMessage, ElMessageBox } from 'element-plus'
import { RTL } from 'element-plus/es/components/virtual-list/src/defaults';

// 获取员工数据相关代码
const currentPage = ref(1)
const pageSize = ref(5)
const disabled = ref(false)
const total = ref(0)
const tableData = ref([])
// 账户状态映射关系
const statusMapping = {
    0: '禁用',
    1: '启用'
}
const handleSizeChange = (val) => {
    userLogin();
}
const handleCurrentChange = (val) => {
    userLogin()
}
// 获取员工数据方法
const userLogin = async () => {
    const params = {
        page: currentPage.value,
        pageSize: pageSize.value,
        name: undefined
    }
    //调用接口,获取员工数据
    let result = await getEmployeeList(params);
    if (result.code === 1) {
        tableData.value = result.data.records || []
        total.value = result.data.total
        return;
    } else {
        return;
    }
}
userLogin();
// 计算属性：转换账户状态显示
const transformedTableData = computed(() => {
    return tableData.value.map(item => {
        return {
            ...item,
            status: statusMapping[item.status]
        }
    })
})
// 添加员工相关代码
const drawer = ref(false)
const addEmployeeData = ref({
    idNumber: "",
    name: "",
    password: "",
    phone: "",
    sex: "1",
    status: 1,
    username: ""
})
// 计算属性：转换账户状态显示
const transformedStatus = computed({
    get() {
        return addEmployeeData.value.status === 0 ? '禁用' : '启用'
    },
    set(value) {
        addEmployeeData.value.status = value === '禁用' ? 0 : 1
    }
})
const transformedSex = computed({
    get() {
        return addEmployeeData.value.sex === '0' ? '女' : '男'
    },
    set(value) {
        addEmployeeData.value.sex = value === '女' ? '0' : '1';
    }
})
function qc() {
    addEmployeeData.value = {
        id: null,
        idNumber: "",
        name: "",
        password: "",
        phone: "",
        sex: '1',
        status: 1,
        username: ""
    }
}
const handleClose = (done) => {
    ElMessageBox.confirm('您确定要关闭它吗？',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
        })
        .then(() => {
            done();
            qc();
        })
        .catch(() => {
            // catch error
        })
}
function cancelClick() {
    drawer.value = false
    qc();
}
function confirmClick() {
    ElMessageBox.confirm(
        `您是否确认选择=> ${addEmployeeData.value.name} ?`,
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
        })
        .then(() => {
            submitForm(employeeDataref)
                .then((result) => {
                    if(result){
                       if (t.value == '添加员工') {
                        addEmployee();
                    } else if (t.value == '编辑员工') {
                        editEmployee();
                    } else {
                        ElMessage.error('无法判断类别')
                    }
                    location.reload();
                    return; 
                    }
                    ElMessage.error('校验不通过')
                }).catch(()=>{
                })
            // 处理结果为 false 的情况
        })
        .catch(() => {
            // catch error
        })
}
//添加员工方法
const addEmployee = async () => {
    //调用接口,获取员工数据
    let result = await addEmployeeApi(addEmployeeData.value);
    if (result.code === 1) {
        ElMessage.success('添加成功');
        // userLogin();
        return;
    } else {
        ElMessage.error(result.msg ? result.msg : '添加失败');
        // userLogin();
        return;
    }
}
// 显示抽屉
const t = ref('')
const XSDrawer = (xst) => {
    drawer.value = true;
    t.value = xst;
}
//修改员工方法
const bg = (row, xst) => {
    XSDrawer(xst);
    // 拷贝数据
    addEmployeeData.value.id = row.id;
    addEmployeeData.value.idNumber = row.idNumber;
    addEmployeeData.value.name = row.name;
    addEmployeeData.value.phone = row.phone;
    addEmployeeData.value.sex = row.sex;
    addEmployeeData.value.status = row.status === '禁用' ? 0 : 1;
    addEmployeeData.value.username = row.username;
}
const editEmployee = async () => {
    //调用接口,获取员工数据
    let result = await editEmployeeApi(addEmployeeData.value);
    if (result.code === 1) {
        ElMessage.success('修改成功');
        // userLogin();
        return;
    } else {
        ElMessage.error(result.msg ? result.msg : '修改失败');
        // userLogin();
        return;
    }
}
// 删除员工方法 deleteEmployeeApi
const deleteEmployee = async (row) => {
    //调用接口,获取员工数据
    let result = await deleteEmployeeApi(row.id);
    if (result.code === 1) {
        ElMessage.success('删除成功');
        userLogin();
        return;
    } else {
        ElMessage.error(result.msg ? result.msg : '删除失败');
        userLogin();
        return;
    }
}
// 表单数据校验
const employeeDataref = ref(null);
var phonereg = /^1[3456789]\d{9}$/;
var idNumberreg = /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/;
const employeeDataRules = {
    idNumber: [
        { required: true, message: '请输入身份证号', trigger: 'blur' },
        { pattern: idNumberreg, message: '身份证号格式不正确', trigger: 'blur' }
    ],
    name: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
    ],
    phone: [
        { required: true, message: '请输入手机号', trigger: 'blur' },
        { pattern: phonereg, message: '手机号码格式不正确', trigger: 'blur' }
    ],
    sex: [
        { required: true, message: '请选择性别', trigger: 'blur' },
    ],
    status: [
        { required: true, message: '请选择账号状态', trigger: 'blur' },
    ],
    username: [
        { required: true, message: '请输入账户名', trigger: 'blur' },
    ],

}
const submitForm = (fromEL) => {
    return new Promise((resolve, reject) => {
        fromEL.value.validate((valid) => {
            if (valid) {
                resolve(true);
            } else {
                resolve(false);
            }
        })
    });
}
</script>
<template>
    <el-card class="page-container">
        <template #header>
            <div class="header">
                <span>员工管理</span>
                <div class="extra">
                    <el-button type="primary" style="margin-left: 16px" @click="XSDrawer('添加员工')">
                        添加员工
                    </el-button>
                    <el-drawer v-model="drawer" :direction="RTL" :with-header="false" size="50%"
                        :before-close="handleClose">
                        <template #default>
                            <div>
                                <h4>{{ t }}</h4>
                                <el-form ref="employeeDataref" :model="addEmployeeData" :rules="employeeDataRules">
                                    <el-form-item label="用户名" prop="name">
                                        <el-input v-model="addEmployeeData.name" />
                                    </el-form-item>
                                    <el-form-item label="账户名" prop="username">
                                        <el-input v-model="addEmployeeData.username" />
                                    </el-form-item>
                                    <el-form-item label="手机号" prop="phone">
                                        <el-input v-model="addEmployeeData.phone" />
                                    </el-form-item>
                                    <el-form-item label="性别" prop="sex">
                                        <el-radio-group v-model="transformedSex">
                                            <el-radio label="男" />
                                            <el-radio label="女" />
                                        </el-radio-group>
                                    </el-form-item>
                                    <el-form-item label="身份证号" prop="idNumber">
                                        <el-input v-model="addEmployeeData.idNumber" />
                                    </el-form-item>
                                    <el-form-item label="账号状态" prop="status">
                                        <el-radio-group v-model="transformedStatus">
                                            <el-radio label="启用" />
                                            <el-radio label="禁用" />
                                        </el-radio-group>
                                    </el-form-item>
                                    <el-form-item label="密码">
                                        <el-input v-model="addEmployeeData.password" />
                                    </el-form-item>
                                </el-form>
                            </div>
                        </template>
                        <template #footer>
                            <div style="flex: auto">
                                <el-button @click="cancelClick">取消</el-button>
                                <el-button type="primary" @click="confirmClick">确认</el-button>
                            </div>
                        </template>
                    </el-drawer>
                </div>
            </div>
        </template>
        <el-table :data="transformedTableData" stripe style="width: 100%" :cell-style="{ textAlign: 'center' }"
            :header-cell-style="{ 'text-align': 'center' }">
            <el-table-column label="序号" width="100" type="index"> </el-table-column>
            <el-table-column label="用户名" prop="name"></el-table-column>
            <el-table-column label="账户名" prop="username"></el-table-column>
            <el-table-column label="手机号" prop="phone"></el-table-column>
            <el-table-column label="账户状态" prop="status">
            </el-table-column>
            <el-table-column label="操作">
                <template #default="{ row }">
                    <el-button type="primary" :icon="Edit" circle @click="bg(row, '编辑员工')" />
                    <el-button type="danger" :icon="Delete" circle @click="deleteEmployee(row)" />
                </template>
            </el-table-column>
            <template #empty>
                <el-empty description="没有数据" />
            </template>
        </el-table>
        <div>
            <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :disabled="disabled"
                :page-sizes="[5, 10, 15, 20]" layout="total, sizes, prev, pager, next, jumper" :total="total"
                @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </div>
    </el-card>
</template>

<style lang="scss" scoped>
.page-container {
    min-height: 100%;
    box-sizing: border-box;

    .header {
        display: flex;
        align-items: center;
        justify-content: space-between;
    }
}

.el-pagination {
    margin-top: 10px;
    justify-content: center;
}
</style>